<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['wb:wbBanner:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['wb:wbBanner:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['wb:wbBanner:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wb:wbBanner:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wbBannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="图片" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          {{ scope.row.type == 1 ? "轮播" : "简介" }}
        </template>
      </el-table-column>
      <el-table-column label="是否展示" align="center" prop="showOrNot">
        <template slot-scope="scope">
          {{ scope.row.showOrNot == 1 ? "是" : "否" }}
        </template>
      </el-table-column>

      <el-table-column label="排序" align="center" prop="sort" />

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['wb:wbBanner:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['wb:wbBanner:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改banner图片对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="图片" prop="img">
          <image-upload v-model="form.img" @numberImg="handleImgChange" />

        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">轮播</el-radio>
            <el-radio :label="2">简介</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否展示" prop="showOrNot">
          <el-switch v-model="form.showOrNot" active-color="#13ce66" :active-value="1" :inactive-value="2"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>

        <div v-for="(value, index) in sourceIds" :key="index">
          <el-form-item label="跳转商品ID">
            <el-input v-model="sourceIds[index]" placeholder="请输入商品ID"/>
          </el-form-item>
        </div>


        <el-form-item label="关联商品">
          <span>{{ form.goodName }}</span>
          <el-button type="primary" style="margin-left: 10px" @click="presentGoods()">选择商品</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <!-- 选择商品 -->
      <el-dialog title="商品选择" :visible.sync="detailOpen" width="800px" append-to-body>
        <el-table ref="goodsTable" :data="goodsDetailList" tooltip-effect="dark" style="width: 100%" height="600px"
          @select="handleSelectionChange1">
          <!-- 全选框列 -->
          <el-table-column type="selection" :width="50" align="center" />

          <el-table-column prop="goodId" label="ID" :width="80" align="center" />

          <el-table-column prop="goodName" label="名称">
            <template slot-scope="{ row }">
              <div style="display: flex; align-items: center">
                <div class="agents-img">
                  <image-preview :src="row.goodImg" :height="50" :width="50"></image-preview>
                </div>
                <div class="agents-info">{{ row.goodName }}</div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="show_center">
          <el-button type="primary" @click="menuAdd()">{{
            showSearch ? "选择" : "确认"
          }}</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import {
  listWbBanner,
  getWbBanner,
  delWbBanner,
  addWbBanner,
  updateWbBanner,
  listGoodVo,
} from "@/api/system/banner";
import {
  selectGiftBag,
  selectGiftBagCommodity,
  editPutGiftBagCommodity,
  editPostGiftBagCommodity,
  delectGiftBagCommodity,
} from "@/api/inventory/giftBag";
export default {
  name: "banner",
  data() {
    return {
      sourceIds: [],
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      goodsDetailList: [],
      // 是否显示弹出层
      editOpen: false,
      detailOpen: false,
      // 总条数
      total: 0,
      // banner图片表格数据
      wbBannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        type: 1,
        isShow: true,
      },
      // 表单校验
      rules: {
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        showOrNot: [
          { required: true, message: "请选择是否展示", trigger: "change" },
        ],
      },
      selectedRows: [],
    };
  },
  created() {
    this.getList();
    this.handleQueryDetail();
  },
  methods: {
    handleImgChange(val) {
      if (val == "+") {
        this.sourceIds.push('');
      } else {
        this.sourceIds.splice(val, 1);

      }
    },
    presentGoods() {
      this.detailOpen = true;
      this.selectedRows = [];

      this.$refs.goodsTable.clearSelection();
    },
    //升级商品查询
    handleQueryDetail() {
      this.goodsDetailList = [];
      this.queryParams.flag = 1;
      let queryParams = {
        pageNum: 1,
        pageSize: 99999,
        flag: 1,
      };
      listGoodVo(queryParams).then((response) => {
        this.goodsDetailList = response.rows;
      });
    },

    // 监听表格的选中变化
    handleSelectionChange1(selections, row) {
      // 选择项大于1时
      if (selections.length > 1) {
        //用于多选表格，清空用户的选择
        this.$refs.goodsTable.clearSelection();
        // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        this.$refs.goodsTable.toggleRowSelection(row, true);
        selections.shift();
        this.selectedRows = selections; // 更新选中的行数据
      } else {
        this.selectedRows = selections; // 更新选中的行数据
      }
    },

    //选择商品
    menuAdd() {
      this.form.goodId = this.selectedRows[0].id;
      this.form.goodName = this.selectedRows[0].goodName;

      this.detailOpen = false;
    },

    /** 查询banner图片列表 */
    getList() {
      this.loading = true;
      listWbBanner(this.queryParams).then((response) => {
        this.wbBannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        img: null,
        isShow: true,
        createTime: null,
        updateTime: null,
        url: null,
        sort: null,
        goodId: null,
        goodName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加banner图片";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getWbBanner(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.sourceIds = response.data.urls.split(',');
        this.title = "修改banner图片";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.urls = this.sourceIds.join(',');
      this.$refs["form"].validate((valid) => {
        if (valid) {

          this.form.img = this.form.img.split(',').map((item) => {
            if (item.indexOf("http") == -1) {
            // this.form.img = this.baseURL + this.form.img;
              return this.baseURL + item;
            }
            return item;
          }).join(',');

        console.log(this.form.img)


          if (this.form.id != null) {
            updateWbBanner(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWbBanner(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除banner图片编号为"' + ids + '"的数据项？')
        .then(function () {
          return delWbBanner(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "wb/wbBanner/export",
        {
          ...this.queryParams,
        },
        `wbBanner_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
.show_center {
  margin: 10px auto;
  display: flex;
  justify-content: center;
}

.agents-img {
  margin-right: 10px;
}
</style>
